package com.kye.express.business.jpush;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.kye.base.Logger;
import com.kye.express.utils.StringUtils;
import com.kye.model.ApiService;
import com.kye.model.UserSession;
import com.kye.model.base.RetrofitManager;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.jpush.PushCommentModel;
import com.kye.model.bean.jpush.PushFeedbackModel;
import com.kye.model.bean.jpush.PushCustomMessageModel;
import com.kye.model.bean.jpush.PushHttpLogModel;
import com.kye.model.bean.jpush.PushNewsModel;
import com.kye.model.bean.jpush.PushPlaceOrderModel;
import com.kye.model.bean.jpush.PushSplashModel;
import com.kye.model.bean.jpush.PushType;
import com.kye.model.bean.waybill_search.RequestWaybillQuery;
import com.kye.model.bean.waybill_search.ResultWaybillQuery;
import com.kye.model.service.WaybillQueryService;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

/**
 * 极光消息推送接收器
 */
public class JpushRecevied extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        Bundle bundle = intent.getExtras();

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Logger.d("JPush用户注册成功,regId:" + regId);
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {//自定义消息
            String message = bundle.getString(JPushInterface.EXTRA_EXTRA);
            Logger.d("收到的自定义消息:" + message);
            processCustomMessage(context, message);
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {//普通广播通知
            Logger.d("接受到推送下来的通知");
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Logger.d("用户点击打开了通知");
        } else {
            Logger.d("Unhandle intent - " + intent.getAction());
        }

    }

    /**
     *
     * 1-新闻-all 2-消息-all 3-订单-alias 4-登录-tag 5-登录-rid 6-内部app发通知-all 7-回复评论通知-rid 8-一级评论通知-rid 9-反馈通知-rid     10-下载日志推送-rid
     * @param context
     * @param message
     */
    private void processCustomMessage(Context context, String message) {
        try {
            Gson gson = new Gson();
            PushCustomMessageModel mPushNewsModel = gson.fromJson(message, PushCustomMessageModel.class);
            String msgClass = mPushNewsModel.getMsgClass();
            if ("1".equals(msgClass) || "2".equals(msgClass)) {//新闻消息
                PushNewsModel pushNewsResultModel = gson.fromJson(mPushNewsModel.getMsgResult(), PushNewsModel.class);
                PushSplashModel pushSplashBean = new PushSplashModel();
                pushSplashBean.setPushType(PushType.news);
                pushSplashBean.setPushId((int) System.currentTimeMillis());
                pushSplashBean.setPushBean(new Gson().toJson(pushNewsResultModel));
                pushSplashBean.setTitle(pushNewsResultModel.getTitle());
                pushSplashBean.setContent(pushNewsResultModel.getContInfo());
                new JpushNotificationUtils(context).sendJpushBrodcastPendingIntent(pushSplashBean);

            } else if ("3".equals(msgClass)) {//下单消息
                PushPlaceOrderModel pushPlaceOrderModel = gson.fromJson(mPushNewsModel.getMsgResult(), PushPlaceOrderModel.class);
                PushSplashModel pushSplashBean = new PushSplashModel();
                if (StringUtils.isNullOrEmpty(pushPlaceOrderModel.getMsgId())) {
                    pushSplashBean.setPushType(PushType.other);
                    pushSplashBean.setPushId((int) System.currentTimeMillis());
                    pushSplashBean.setPushBean(new Gson().toJson(pushPlaceOrderModel));
                    pushSplashBean.setTitle(pushPlaceOrderModel.getTitle());
                    pushSplashBean.setContent(pushPlaceOrderModel.getContInfo());
                    new JpushNotificationUtils(context).sendJpushBrodcastPendingIntent(pushSplashBean);
                } else {
                    if (pushPlaceOrderModel.getType().equals("1")) {
                        pushSplashBean.setPushType(PushType.order);
                        pushSplashBean.setPushId((int) System.currentTimeMillis());
                        pushSplashBean.setPushBean(new Gson().toJson(pushPlaceOrderModel));
                        pushSplashBean.setTitle(pushPlaceOrderModel.getTitle());
                        pushSplashBean.setContent(pushPlaceOrderModel.getContInfo());
                        new JpushNotificationUtils(context).sendJpushBrodcastPendingIntent(pushSplashBean);
                    } else if (pushPlaceOrderModel.getType().equals("2")) {
                        doExpressSeach(context, pushPlaceOrderModel);
                    }
                }
            } else if ("5".equals(msgClass)) {//下线通知
                PushPlaceOrderModel mPushPlaceOrderModel = gson.fromJson(mPushNewsModel.getMsgResult(), PushPlaceOrderModel.class);
                if (mPushPlaceOrderModel != null) {
                    if (isUserLogin()) {
                        PushSplashModel pushSplashBean = new PushSplashModel();
                        pushSplashBean.setPushType(PushType.otherLogin);
                        pushSplashBean.setPushId((int) System.currentTimeMillis());
                        pushSplashBean.setPushBean(new Gson().toJson(mPushPlaceOrderModel));
                        pushSplashBean.setTitle(mPushPlaceOrderModel.getTitle());
                        pushSplashBean.setContent(mPushPlaceOrderModel.getContInfo());
                        if (JpushNotificationUtils.checkApkExist(context)) {// 判断应用是否启动
                            if (!JpushNotificationUtils.isApplicationBroughtToBackground(context)) { //判断应用是否在后台
                                JPushResponseParseHelper.getInstance().init(context, pushSplashBean).startParseJPushResponse();
                            } else {
                                JpushNotificationUtils.savePushSplashBean(pushSplashBean);
                            }
                        } else {
                            JpushNotificationUtils.savePushSplashBean(pushSplashBean);
                        }
                    }
                }
            } else if ("6".equals(msgClass)) {//弹窗通知
                PushNewsModel pushNewsResultModel = gson.fromJson(mPushNewsModel.getMsgResult(), PushNewsModel.class);
                int id = (int) System.currentTimeMillis();
                PushSplashModel mPushSplashBean = new PushSplashModel();
                mPushSplashBean.setPushId(id);
                mPushSplashBean.setPushBean(new Gson().toJson(pushNewsResultModel));
                mPushSplashBean.setTitle(pushNewsResultModel.getTitle());
                mPushSplashBean.setContent(pushNewsResultModel.getContInfo());
                mPushSplashBean.setPhoneNumber(pushNewsResultModel.getPhoneNumber());
                mPushSplashBean.setPushType(PushType.noticeDialog);

                if (JpushNotificationUtils.checkApkExist(context)) {// 判断应用是否启动
                    if (JpushNotificationUtils.isApplicationBroughtToBackground(context)) { //判断应用是否在后台
                        new JpushNotificationUtils(context).sendJpushBrodcastPendingIntent(mPushSplashBean);
                    } else {
                        JPushResponseParseHelper.getInstance().init(context, mPushSplashBean).startParseJPushResponse();
                    }
                } else {
                    new JpushNotificationUtils(context).sendJpushBrodcastPendingIntent(mPushSplashBean);
                }
            } else if ("7".equals(msgClass) || "8".equals(msgClass)) {//7 通知二级评论  //8 通知一级评论
                if (isUserLogin()) {
                    PushCommentModel pushCommentModel = gson.fromJson(mPushNewsModel.getMsgResult(), PushCommentModel.class);
                    PushSplashModel pushSplashBean = new PushSplashModel();
                    if ("7".equals(msgClass)) {
                        pushSplashBean.setPushType(PushType.commentTwo);
                    } else {
                        pushSplashBean.setPushType(PushType.commentOne);
                    }
                    pushSplashBean.setPushId((int) System.currentTimeMillis());
                    pushSplashBean.setPushBean(new Gson().toJson(pushCommentModel));
                    pushSplashBean.setTitle(pushCommentModel.getCommentTitle());
                    pushSplashBean.setContent(pushCommentModel.getContent());
                    new JpushNotificationUtils(context).sendJpushBrodcastPendingIntent(pushSplashBean);
                }
            } else if ("9".equals(msgClass)) {
                PushFeedbackModel mNotifyFeedbackbean = gson.fromJson(mPushNewsModel.getMsgResult(), PushFeedbackModel.class);
                if (mNotifyFeedbackbean != null) {
                    int id = (int) System.currentTimeMillis();
                    mNotifyFeedbackbean.setNotifyId(id);
                    PushSplashModel mPushSplashBean = new PushSplashModel();
                    mPushSplashBean.setPushId(id);
                    mPushSplashBean.setPushBean(new Gson().toJson(mNotifyFeedbackbean));
                    mPushSplashBean.setTitle(mNotifyFeedbackbean.getTitle());
                    mPushSplashBean.setContent(mNotifyFeedbackbean.getContInfo());
                    mPushSplashBean.setPushType(PushType.feedBack);

                    if (JpushNotificationUtils.checkApkExist(context)) {// 判断应用是否启动
                        if (JpushNotificationUtils.isApplicationBroughtToBackground(context)) { //判断应用是否在后台
                            new JpushNotificationUtils(context).sendJpushBrodcastPendingIntent(mPushSplashBean);
                        } else {
                            JPushResponseParseHelper.getInstance().init(context, mPushSplashBean).startParseJPushResponse();
                        }
                    } else {
                        new JpushNotificationUtils(context).sendJpushBrodcastPendingIntent(mPushSplashBean);
                    }
                }
            } else if ("10".equals(msgClass)) {//上传接口日志通知
                PushHttpLogModel jPushHttpLogBean = gson.fromJson(mPushNewsModel.getMsgResult(), PushHttpLogModel.class);
                int id = (int) System.currentTimeMillis();
                PushSplashModel mPushSplashBean = new PushSplashModel();
                mPushSplashBean.setPushId(id);
                mPushSplashBean.setPushBean(new Gson().toJson(jPushHttpLogBean));
                mPushSplashBean.setPushType(PushType.sendLog);
                if (JpushNotificationUtils.checkApkExist(context)) {// 判断应用是否启动
                    JPushResponseParseHelper.getInstance().init(context, mPushSplashBean).startParseJPushResponse();
                } else {
                    JpushNotificationUtils.savePushSplashBean(mPushSplashBean);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 查询运单详情
     *
     * @param context
     * @param pushPlaceOrderModel
     */
    public void doExpressSeach(final Context context, final PushPlaceOrderModel pushPlaceOrderModel) {
        if (pushPlaceOrderModel != null && !TextUtils.isEmpty(pushPlaceOrderModel.getMsgId())) {
            Single<OpenApiResult<ResultWaybillQuery>> singleResult = RetrofitManager.getInstance().createOpenApiService(WaybillQueryService.class).
                    waybillQuery(new RequestWaybillQuery(pushPlaceOrderModel.getMsgId(), UserSession.getInstance().getUser().getPhone()));
            singleResult.observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SingleObserver<OpenApiResult<ResultWaybillQuery>>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onSuccess(OpenApiResult<ResultWaybillQuery> resultWaybillQueryOpenApiResult) {
                            if (resultWaybillQueryOpenApiResult != null && resultWaybillQueryOpenApiResult.isSuccess()) {
                                PushSplashModel pushSplashBean = new PushSplashModel();
                                pushSplashBean.setPushType(PushType.express);
                                pushSplashBean.setPushId((int) System.currentTimeMillis());
                                pushSplashBean.setPushBean(new Gson().toJson(resultWaybillQueryOpenApiResult));
                                pushSplashBean.setTitle(pushPlaceOrderModel.getTitle());
                                pushSplashBean.setContent(pushPlaceOrderModel.getContInfo());
                                new JpushNotificationUtils(context).sendJpushBrodcastPendingIntent(pushSplashBean);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {

                        }
                    });
        }
    }

    private boolean isUserLogin() {
        return UserSession.getInstance().getUser() != null && UserSession.getInstance().getUser().isLogin();
    }
}